package icu.d4peng.basic.satoken.spring.context.path;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import cn.dev33.satoken.application.ApplicationInfo;
import cn.dev33.satoken.util.SaFoxUtil;

/**
 * ApplicationContextPathLoading:上下文路径配置
 *
 * @author d4peng <a href="d4peng@qq.com">d4peng@qq.com</a>
 * @since 2023.12.02
 */
public class ApplicationContextPathLoading implements ApplicationRunner {

	@Value("${server.servlet.context-path:}")
	private String contextPath;

	@Value("${spring.mvc.servlet.path:}")
	private String servletPath;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		String routePrefix = "";

		if (SaFoxUtil.isNotEmpty(contextPath)) {
			if (!contextPath.startsWith("/")) {
				contextPath = "/" + contextPath;
			}
			if (contextPath.endsWith("/")) {
				contextPath = contextPath.substring(0, contextPath.length() - 1);
			}
			routePrefix += contextPath;
		}

		if (SaFoxUtil.isNotEmpty(servletPath)) {
			if (!servletPath.startsWith("/")) {
				servletPath = "/" + servletPath;
			}
			if (servletPath.endsWith("/")) {
				servletPath = servletPath.substring(0, servletPath.length() - 1);
			}
			routePrefix += servletPath;
		}

		if (SaFoxUtil.isNotEmpty(routePrefix) && !routePrefix.equals("/")) {
			ApplicationInfo.routePrefix = routePrefix;
		}
	}

}